package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public List<SysUser> findUsers(SysUser entity) {
        return sysUserDao.selectUsers(entity);
    }

    @Override
    public SysUser findById(Integer id) {
        SysUser sysUser = sysUserDao.selectById(id);
        if (sysUser==null)
            throw new ServiceException("没有找到对应的用户");

        List<Integer> list = sysUserRoleDao.selectRoleIdsByUserId(id);
        sysUser.setRoleIds(list);
        return sysUser;
    }

    @Override
    public int saveUser(SysUser entity) {
        //对密码进行MD5加密
        String password=entity.getPassword();
        //通过UUID随机数当做“盐”值
        String salt= UUID.randomUUID().toString();
        //algorithmName：加密形式（具体支持哪些算法，请自行百度）
        //source：简单理解就是传入的原始明文密码值
        //salt：盐值
        //hashIterations：加密次数(默认一次，可查看源码)
        SimpleHash md5 = new SimpleHash("MD5", password, salt, 1);
        password=md5.toHex();//将加密后的密码转为十六进制
        entity.setPassword(password);
        entity.setSalt(salt);

        int i = sysUserDao.insertUser(entity);
        sysUserRoleDao.insertUserRoles(entity.getId(),entity.getRoleIds());
        return i;
    }

    @Override
    public int updateUser(SysUser entity) {
        int i = sysUserDao.updateUser(entity);
        if (i==0)
            throw new ServiceException("记录可能不存在");

        sysUserRoleDao.deleteByUserId(entity.getId());
        sysUserRoleDao.insertUserRoles(entity.getId(),entity.getRoleIds());
        return i;
    }

    /**
     * 更新用户状态
     * @param id
     * @param valid
     * @return
     * @RequiresPermission 注解由shiro框架定义，基于此注解定义授权切入点方法
     * 也就是说用户访问此方法时，需要授权才可以访问。shiro框架底层会基于登录用户
     * 获取登录用户权限(菜单的权限标识)，然后判定用户权限中是否包含@RequiresPermissions注解中定义的权限标识
     */
    @Override
    public int validById(Integer id,Integer valid){
        int i = sysUserDao.validById(id, valid, "admin");
        if (i==0)
            throw new ServiceException("记录可能不存在了");
        return i;
    }

}
